package com.gourd.file.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.gourd.common.rbac.entity.RbacUser;
import com.gourd.common.rbac.service.RbacUserService;
import com.gourd.common.utils.CollectionCopyUtil;
import com.gourd.common.utils.DateUtil;
import com.gourd.common.utils.ExcelUtil;
import com.gourd.file.excel.entity.UserExcel;
import com.gourd.file.excel.service.ExcelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author gourd
 */
@RestController
@RequestMapping("/excel")
@Api(tags = "excel", description = "excel控制器")
public class ExcelController {

    @Autowired
    private RbacUserService userService;

    @Autowired
    private ExcelService excelService;

    @GetMapping("/single-export")
    @ApiOperation(value="导出")
    public void export(HttpServletResponse response) {
        // 模拟从数据库获取需要导出的数据
        List<RbacUser> personList = userService.findAll();
        List<UserExcel> userExcelList =  CollectionCopyUtil.copyList(personList,UserExcel.class);
        //导出操作
        ExcelUtil.exportExcel(userExcelList,"用户列表","用户", UserExcel.class,"用户信息"+ DateUtil.date2Str(new Date(),"YYYY-MM-dd-HH-mm") +".xls",response);

    }

    @GetMapping("/sheets-export")
    @ApiOperation(value="导出多个sheet")
    public void exportSheets(HttpServletResponse response) {
        excelService.exportSheets(response);
    }

    @PostMapping("/import")
    @ApiOperation(value="导入")
    public void importExcel(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);

        // 需要验证
        importParams.setNeedVerfiy(true);

        try {
            ExcelImportResult<RbacUser> result = ExcelImportUtil.importExcelMore(file.getInputStream(), RbacUser.class,
                    importParams);

            List<RbacUser> successList = result.getList();
            for (RbacUser demoExcel : successList) {
              System.out.println(demoExcel);
            }
        } catch (IOException e) {
        } catch (Exception e) {
        }
    }
}